<template>
  <tool-header>
    {{title}}
  </tool-header>
  <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-form-item label="Input" v-bind="validateInfos.base64Input">
      <a-textarea v-model:value="modelRef.base64Input" :rows="4" />
    </a-form-item>
    <a-form-item label="Output">
      <a-textarea v-model:value="base64Output" :rows="4" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click.prevent="onSubmit">Create</a-button>
      <a-button style="margin-left: 10px" @click="reset">Reset</a-button>
    </a-form-item>
  </a-form>
</template>
<script lang="ts" setup>
import { reactive, toRaw, computed, onRenderTriggered } from 'vue';
import { Form } from 'ant-design-vue';
import { useRoute } from 'vue-router'
import ToolHeader from '../ToolHeader.vue'
import {str, bytesToString} from '@scure/base'
import * as baseEncode from '@scure/base'

const useForm = Form.useForm;
const route = useRoute();
const title = route.query.title


const labelCol = { span: 4 };
const wrapperCol = { span: 14 };

const modelRef = reactive({
  base64Input: ''
});



const base64Output = computed(() => {
  let method = route.query.method
  let encode:string = <string>route.query.encode
  if (method == 'encode') {
    let data = new TextEncoder().encode(modelRef.base64Input);
    return baseEncode[encode].encode(data);
  } else {
    try {
      let data:Uint8Array = baseEncode[encode].decode(modelRef.base64Input)
      return new TextDecoder().decode(data)
    } catch(e) {
      console.log(e);
      return 'Incorrect format'
    }
  }
})
const { resetFields, validate, validateInfos } = useForm(
  modelRef,
  reactive({
    base64Input: [
      {
        required: true,
        message: 'Please input Base64 encoding',
      },
    ]
  }),
);
const onSubmit = () => {
  validate()
    .then(res => {
      console.log(res, toRaw(modelRef));
    })
    .catch(err => {
      console.log('error', err);
    });
};
const reset = () => {
  resetFields();
};
</script>